﻿Imports System.Linq
Imports HTLibrary
Imports TNCBAL
Imports TNCDAL

Public Class ucCustomer
    'Customer's Company
    Public _objCurrCompany As tblCompany

    Private _objCustomerController As New CustomerController
    Private _objCurrCustomer As tblCustomer

    Public Sub New()
        InitializeComponent()
        TextBoxHelper.TextBox_InitUpperStringEvent(Me.Controls)
        TextBoxHelper.TextBox_InitNonAlphabetCharEvent(Me.Controls, New List(Of String)({"txtTel"}))
        DataGridViewHelper.DataGridView_InitEvent(gridView)
        InitCommands()
    End Sub

    Private Sub ucContactEmployee_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        FormatDataGridView()
        'EnableButtons(False)
    End Sub

    Public Sub BindDataGridView(ByVal columnName As String, ByVal someText As Integer)
        Dim query As IQueryable(Of tblCustomer) = _objCustomerController.GetCustomerByCompany(_objCurrCompany.ID_Company)
        'Dim source As New BindingSource
        'source.DataSource = query
        gridView.DataSource = query
        'BindingNavigator1.BindingSource = source

        Dim indexRow As Integer = CViewer.GetIndexRowInDataGridViewByTextSearch(gridView, columnName, someText)
        If indexRow >= 0 Then
            For Each col As DataGridViewColumn In gridView.Columns
                If col.Visible Then
                    gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                    Exit For
                End If
            Next

        End If

        'Nếu không tồn tại row nào
        If gridView.Rows.Count = 0 Then
            ResetControls() 'reset hết các control
        End If
        'disable 2 nút edit và delete nếu row count = 0
        _ucCommands.EnableButtons(False, gridView.Rows.Count)
    End Sub

    Public Sub BindDataGridView(Optional ByVal indexRow As Integer = -1)
        'ResetControls()
        Dim query As IQueryable(Of tblCustomer) = _objCustomerController.GetCustomerByCompany(_objCurrCompany.ID_Company)
        gridView.DataSource = query

        If indexRow > 0 Then
            'Set current row
            'dataGridViewCustomer.Rows(indexRow).Selected = True
            'dataGridViewCustomer.FirstDisplayedScrollingRowIndex = indexRow
            For Each col As DataGridViewColumn In gridView.Columns
                If col.Visible Then
                    gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                    Exit For
                End If
            Next
        End If

        'Nếu không tồn tại row nào
        If gridView.Rows.Count = 0 Then
            ResetControls() 'reset hết các control
        End If
        'disable 2 nút edit và delete nếu row count = 0
        _ucCommands.EnableButtons(False, gridView.Rows.Count)
    End Sub

    Public Sub FormatDataGridView()
        Dim hideColumns As New List(Of String)({"Id_Customer", "tblCompany", "Id_Company", "IsActive"})
        Dim renameColumns As New Dictionary(Of String, String)
        renameColumns.Add("CustomerName", "Employee")
        CViewer.FormatDataGridView(gridView, hideColumns, renameColumns)
    End Sub

    Public Sub LoadForm()
        'show result
        txtName.Text = _objCurrCustomer.CustomerName
        txtTel.Text = _objCurrCustomer.Tel
        txtEmail.Text = _objCurrCustomer.Email
        'chkIsActive.Checked = _objCurrCustomer.IsActive
    End Sub

    Public Sub ResetControls()
        CViewer.ResetControls(Me.Controls)


        'Init obj
        _objCurrCustomer = New tblCustomer
        _objCurrCustomer.IsActive = True

        'txtName.Text = ""
        'txtTel.Text = ""
        'txtEmail.Text = ""
        ''chkIsActive.Checked = True
    End Sub

    Public Sub GetInfoByForm()
        With _objCurrCustomer
            .CustomerName = txtName.Text
            .Tel = txtTel.Text
            .Email = txtEmail.Text
            .ID_Company = _objCurrCompany.ID_Company
            '.IsActive = chkIsActive.Checked
        End With
    End Sub

#Region "Commands"
    ''' <summary>
    ''' Init commands
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub InitCommands()
        '_ucCommands = New ucCommands(Me, controlCollect)
        _ucCommands.InitControl(Me)
        _ucCommands.ShowHideButtons(True, True, True)
        _ucCommands.btnAddEvent_Click = New EventHandler(AddressOf btnAdd_Click)
        _ucCommands.btnEditEvent_Click = New EventHandler(AddressOf btnEdit_Click)
        _ucCommands.btnDeleteEvent_Click = New EventHandler(AddressOf btnDel_Click)
        _ucCommands.btnUpdateEvent_Click = New EventHandler(AddressOf btnUpdate_Click)
        _ucCommands.btnCancelEvent_Click = New EventHandler(AddressOf btnCancel_Click)
        _ucCommands.Dock = DockStyle.Fill
    End Sub

    Public Sub FocusControl()
        txtName.Focus()
        txtName.SelectionLength = 0
    End Sub


    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'EnableButtons(True)
        ResetControls()
        FocusControl()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'EnableButtons(True)
        FocusControl()
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If MessageBox.Show("Delete this record?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
            Try
                Dim indexRow As Integer = gridView.CurrentRow.Index
                _objCurrCustomer.IsActive = False
                _objCustomerController.Update(_objCurrCustomer)

                'Xóa row tại indexRow và focus sau khi xóa
                gridView.Rows.RemoveAt(indexRow)
                indexRow -= 1
                If indexRow >= 0 Then
                    For Each col As DataGridViewColumn In gridView.Columns
                        If col.Visible Then
                            gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                            Exit For
                        End If
                    Next
                End If

                'Write log
                Dim objLogController As New LogController
                objLogController.Insert(enumAction.Delete, String.Format("Customer Type ({0}) in {1} Company", _objCurrCustomer.CustomerName, _objCurrCustomer.tblCompany.Name))

                'BindDataGridView(indexRow)
                'dataGridViewCustomer.Rows.Remove(dataGridViewCustomer.CurrentRow)
                'If dataGridViewCustomer.Rows.Count = 0 Then
                '    ResetControls()
                'End If
            Catch ex As Exception
#If DEBUG Then
                Throw ex
#Else
                MessageBox.Show(ex.Message)
#End If
            End Try

        End If
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            GetInfoByForm()
            Dim action As enumAction
            'Dim indexRow As Integer = -1
            If _objCurrCustomer.ID_Customer > 0 Then
                _objCustomerController.Update(_objCurrCustomer)
                action = enumAction.Edit
                'indexRow = gridView.CurrentRow.Index
            Else
                _objCustomerController.Insert(_objCurrCustomer)
                action = enumAction.Add
                'indexRow = gridView.Rows.Count
            End If
            'Write log
            Dim objLogController As New LogController
            objLogController.Insert(action, String.Format("Customer Type ({0}) in {1} Company", _objCurrCustomer.CustomerName, _objCurrCustomer.tblCompany.Name))

            'Refresh gridview
            BindDataGridView("ID_Customer", _objCurrCustomer.ID_Customer)
            'BindDataGridView(indexRow)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'EnableButtons(False)
        gridViewContactEmployee_CurrentCellChanged(Nothing, Nothing)
    End Sub
#End Region

    Private Sub gridViewContactEmployee_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gridView.CurrentCellChanged
        'Load info
        Try
            If _ucCommands Is Nothing Then
                Return
            End If

            If gridView.CurrentRow Is Nothing Then
                Return
            End If

            'Kiểm tra nếu đang cập nhật/thêm mới thì không hiển thị dữ liệu
            If _ucCommands.btnUpdate.Enabled Then
                Return
            End If

            'ResetForm()
            Dim id_customer As Integer = gridView.CurrentRow.Cells("ID_Customer").Value
            _objCurrCustomer = _objCustomerController.SelectRecordById(id_customer)

            'Fill company's fields
            LoadForm()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub


End Class
